package com.mskj.zxmy.service.serviceImpl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.mskj.zxmy.dto.CKSQListQueryFo;
import com.mskj.zxmy.dto.PageResult;

import com.mskj.zxmy.entity.*;
import com.mskj.zxmy.mapper.MyTaskMapper;
import com.mskj.zxmy.mapper.NeckMaterialMapper;
import com.mskj.zxmy.service.NeckMaterialService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: zxmy
 * @BelongsPackage: com.mskj.zxmy.service.serviceImpl
 * @Author: lk
 * @CreateTime: 2025-07-23
 * @Description: TODO
 * @Version: 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class NeckMaterialServiceImpl implements NeckMaterialService {

    private final NeckMaterialMapper neckMaterialMapper;
    private final MyTaskMapper myTaskMapper;

    @Override
    public PageResult<RepositoryApplication> lldList(CKSQListQueryFo fo) {
        // 查询总数
        Long total = neckMaterialMapper.countLLdList(fo);
        
        // 计算偏移量
        int offset = (fo.getPageNum() - 1) * fo.getPageSize();
        
        // 查询数据列表
        List<RepositoryApplication> repositoryApplications = neckMaterialMapper.queryLLdListWithPage(fo, offset, fo.getPageSize());
        
        // 处理产品信息
        for (RepositoryApplication repositoryApplication : repositoryApplications) {
            if (repositoryApplication.getAssociatedProducts() != null) {
                Map<String, Object> product = myTaskMapper.getProductById(repositoryApplication.getAssociatedProducts());
                if (product != null) {
                    // 拼接产品信息：产品名称 + 其他属性（示例）
                    String prodInfo =
                                    product.get("productNumber") + " " +               // 产品编号
                                    product.get("productName") + " " +
                                    product.get("brand") + " " +        // 品牌
                                    product.get("materialCategory"); // 规格
                    // 设置拼接后的信息
                    repositoryApplication.setProdInfo(prodInfo);
                }
            }
        }
        
        return new PageResult<>(repositoryApplications, total, fo.getPageNum(), fo.getPageSize());
    }

    @Override
    public Lists scanCkBackInfo(Integer id) {
        Lists lists = neckMaterialMapper.retListsInfoByLLdId(id);
        lists.setCashiersNumber(getMaxCkNo());
        lists.setReceiver(myTaskMapper.getNickNameByMemberIds(getLoginId()).get(0));
        return lists;
    }

    private String getMaxCkNo() {
        String now = LocalDate.now().toString().replace("-", "");
        String prefix = "CK" + now;

        String maxNo = myTaskMapper.getMaxBgSerialNumberCK(prefix);
        if (StringUtils.isBlank(maxNo)) {
            maxNo = prefix + "0001";
        }

        String suffix = String.format("%04d", Integer.parseInt(maxNo.substring(10)) + 1);
        return prefix + suffix;
    }

    @Override
    public List<Ck02CheckoutFormCheckout> scanToGetItem(Integer id) {
        return neckMaterialMapper.scanToGetItem(id);

    }

    private static String getLoginId() {
        String loginId = null;
        try {
            loginId = StpUtil.getLoginId().toString();
        } catch (Exception e) {
            loginId = "6b94424b9c3c422780255d75437eed6a";
        }
        return loginId;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean saveCkd(Lists lists) {
        List<Ck02CheckoutFormCheckout> ckdDetail = lists.getCkdDetail();
        if (CollectionUtil.isEmpty(ckdDetail)) throw new RuntimeException("出库单详情不能为空");
        lists.setReceiver(getLoginId());
        neckMaterialMapper.saveCkd(lists);
        ckdDetail.forEach(cur -> {
            cur.setLinkOutList(lists.getId());
            cur.setNumberOfReleases(cur.getNumberOfTasks());
            cur.setBatchNumber(cur.getBatchBarCodes());
        });
        neckMaterialMapper.saveCkdDetail(ckdDetail);

        BarcodeManagementTable main = myTaskMapper.getBarCodePoByCode(ckdDetail.get(0).getBatchNumber());
        main.setModified1(new Date());
        main.setModified(getLoginId());
        Map<String, Object> process = myTaskMapper.getById(lists.getProcessTaskId());
        main.setProductName(Integer.parseInt(process.get("productInformation").toString()));
        main.setProductionTasks(Integer.parseInt(process.get("associatedTasks").toString()));
        main.setCurrentProcessTask(lists.getProcessTaskId());
        myTaskMapper.updateBarcodeMain(main);

        BarCodeManagementDetails detail = new BarCodeManagementDetails();
        detail.setBindTheProduct(Integer.parseInt(process.get("productInformation").toString()));
        detail.setBarCodeBehavior("");
        detail.setNumber(BigDecimal.valueOf(ckdDetail.stream().mapToDouble(cur -> cur.getNumberOfTasks().doubleValue()).sum()));
        detail.setCreated(new Date());
        detail.setBarCodeBehavior("领料出库");
        detail.setSynchronisingFolderFailedSS(getLoginId());
        detail.setLinkBarCodeManagement(main.getId());
        detail.setLinkProcessTasks(lists.getProcessTaskId());
        detail.setResponsiblePersons(getLoginId());
        myTaskMapper.saveBarcodeDetail(detail);
        return Boolean.TRUE;
    }

}
